

//
//  ThemeManager.m
//  ThemeChange
//
//  Created by 花花 on 2016/12/8.
//  Copyright © 2016年 花花. All rights reserved.
//

#import "ThemeManager.h"
#define kDefaultThemeName   @"Forest"
#define kThemeNameKey   @"kThemeNameKey"
@implementation ThemeManager

+ (instancetype)shareManager{
    static ThemeManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[ThemeManager alloc]init];
    });

    return instance;

}
- (instancetype)init{
    if (self = [super init]) {
        //1.读取plist
        NSString *filePath =[[NSBundle mainBundle]pathForResource:@"theme.plist" ofType:nil];
        //2.初始化self.themeDic  dictionaryWithContentsOfFile 将字典中的内容设置为指定文件中的所有内容
        self.themeDic =[NSDictionary dictionaryWithContentsOfFile:filePath];
        //3.初始化themeName  并使用NSUserDefaults存储主题名
        NSString *themeName = [[NSUserDefaults standardUserDefaults]objectForKey:kThemeNameKey];
        if(themeName){
        
            self.themeName = themeName;
        }else{
        
            self.themeName = kDefaultThemeName;
        }
    }

    return self;
}
//主题文件的完整路径
-(NSString *)themePath{
    //资源目录路径
    NSString *rootPath = [[NSBundle mainBundle]resourcePath];
    NSString *themePath = _themeDic[_themeName];
    return [rootPath stringByAppendingPathComponent:themePath];

}
- (void)setThemeName:(NSString *)themeName{
    
    if (_themeName != themeName) {
        _themeName = [themeName copy];
        
        NSString *themeFilePath =[[self themePath] stringByAppendingPathComponent:@"config.plist"];
        self.themeColorInfoDic = [NSDictionary dictionaryWithContentsOfFile:themeFilePath];
        
        //保存及同步
        [[NSUserDefaults standardUserDefaults]setObject:_themeName forKey:kThemeNameKey];
        [[NSUserDefaults standardUserDefaults]synchronize];
        
     
        
    }
    
}

 //根据图片文件所在的路径读取图片

- (UIImage *)loadImageWithImgName:(NSString *)imageName{
 
    return [UIImage imageWithContentsOfFile:[[self themePath] stringByAppendingPathComponent:imageName]];

}

- (UIColor *)loadColorWithKeyName:(NSString *)colorName{

    if ([_themeColorInfoDic[colorName]count]<3) {
        return nil;
    }
    
    CGFloat red = [_themeColorInfoDic[colorName][@"R"] floatValue];
    CGFloat grenn = [_themeColorInfoDic[colorName][@"G"] floatValue];
    CGFloat blue = [_themeColorInfoDic[colorName][@"B"] floatValue];
    NSNumber *alphaNum =_themeColorInfoDic[colorName][@"alpha"] ;
    CGFloat alpha = alphaNum ?[alphaNum floatValue] :1;
    
    
    return [UIColor colorWithRed:red/255 green:grenn/255 blue:blue/255 alpha:alpha];
    
}

//ThemeTableVC cell里面的主题图片

- (UIImage *)loadThemeImageWithThemeName:(NSString *)themeName{
   
    NSString *filePath =[[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:_themeDic[themeName]] stringByAppendingPathComponent:@"more_icon_theme"];
 
    return [UIImage imageWithContentsOfFile:filePath];
    

}



@end
